/**
 * Created by Administrator on 2017/5/10.
 */
var menuId="1001",thisNum,delId,edit,pageSize=9999;
var countTreeId;
$(function() {
    queryListRole();
    queryListauthority(menuId);
    initDeptTree();
});
//查询
$(".btnSearch").click(function(){
    queryListauthority(menuId);
})
//获取列表菜单
var strzTreeResult;

function initDeptTree(){
    PostForm("/cwp/front/sh/role!execute", "uid=c003", "", getDeptTreedeputy, '');
}
function getDeptTreedeputy(result){
    // for(var i=0;i<result.beans.length;i++){
    //     strzTree += '{"name":"'+result.beans[i].description +'","id":"'+result.beans[i].sortNumber + '","powerId":"' + result.beans[i].id + '","pId":"'+result.beans[i].parentId+'"},';
    // }
    // strzTree += '{"name":"全部","powerId":"","pId":""},';
    strzTreeResult = result;
    PostForm("/cwp/front/sh/role!execute", "uid=c002", "", outputDeptTree, '');
}
//部门选择
function zTreeOnClick(event, treeId, treeNode) {
    var deptId=treeNode.powerId;
    menuId = deptId;
    queryListauthority(deptId);

}


//获取数据初始化部门树
function outputDeptTree(result){
    if(result.returnCode=="0"){
        // 合并组织树数据
        var strzTreeResultFull = result.beans.concat( strzTreeResult.beans );
        var strzTreeData1 = [];
        var strzTreeData2 = [];
        // 拆分组织树
        for(var i=0;i<strzTreeResultFull.length;i++){
            if(strzTreeResultFull[i].sortNumber.length == 4){
                strzTreeResultFull[i].sortNumberParent = '0';
                strzTreeData1.push(strzTreeResultFull[i]);
            }else{
                strzTreeResultFull[i].sortNumberParent = String(strzTreeResultFull[i].sortNumber.slice(0,(strzTreeResultFull[i].sortNumber.length-2)));
                strzTreeData2.push(strzTreeResultFull[i]);
            }
        }
        var strzTree =  "[";
        for(var i=0;i<strzTreeData1.length;i++){
            strzTree += '{"name":"'+strzTreeData1[i].description +'","id":"'+strzTreeData1[i].sortNumber + '","powerId":"' + strzTreeData1[i].id + '","powerPId":"' + strzTreeData1[i].parentId  + '","pId":"'+strzTreeData1[i].sortNumberParent+'"},';
        }
        strzTree += '{"name":"全部","powerId":"","pId":""},';


        //配置组织结构树
        var setting = {

            data: {
                simpleData: {
                    enable: true
                }
            },
            view: {
                showIcon: false
            },
            callback: {
                onClick: zTreeOnClick
            }
        };

        // for(var i=0;i<result.beans.length;i++){
        //     if(i==result.beans.length-1){
        //             strzTree += '{"name":"'+result.beans[i].description +'","id":"'+result.beans[i].sortNumber + '","powerId":"' + result.beans[i].id + '","pId":"'+result.beans[i].parentId+'"}';
        //         break;
        //     }
        //     strzTree += '{"name":"'+result.beans[i].description +'","id":"'+result.beans[i].sortNumber + '","powerId":"' + result.beans[i].id + '","pId":"'+result.beans[i].parentId+'"},';
        // }

        for(var i=0;i<strzTreeData2.length;i++){
            if(i==strzTreeData2.length-1){
                strzTree += '{"name":"'+strzTreeData2[i].description +'","id":"'+strzTreeData2[i].sortNumber + '","powerId":"' + strzTreeData2[i].id + '","powerPId":"' + strzTreeData2[i].parentId + '","pId":"'+strzTreeData2[i].sortNumberParent+'"}';
                break;
            }
            strzTree += '{"name":"'+strzTreeData2[i].description +'","id":"'+strzTreeData2[i].sortNumber + '","powerId":"' + strzTreeData2[i].id + '","powerPId":"' + strzTreeData2[i].parentId + '","pId":"'+strzTreeData2[i].sortNumberParent+'"},';
        }
        strzTree +="]";
        var zNodes=JSON.parse(strzTree);
        $.fn.zTree.init($("#treeOrg"), setting, zNodes );

        var zTree = $.fn.zTree.getZTreeObj("treeOrg");
        var countTreeId = "treeOrg_2";
        if(countTreeId!=undefined && countTreeId!=""){
            var getTreeNode=zTree.getNodeByTId(countTreeId);
            //默认选中节点
            zTree.selectNode(getTreeNode);
            //默认展开节点
            zTree.expandNode(getTreeNode,true);
        }
        getDeptTreeModal(zNodes);
    }
}

//获取所有用户角色
function queryListRole(){
    PostForm("/cwp/front/sh/role!execute", "uid=c001&pageSize="+ pageSize +"&currentPage=1", "", outputListRole, '');
}
function outputListRole(result){
    var outHtml = template("roleListTmpl", result);
    $("#roleList").html(outHtml);
}

//单击角色查询对应权限
function queryListauthority(menuId){
    var queryrequestUid = $("#queryrequestUid").val();
    PostForm("/cwp/front/sh/permission!execute", "uid=permissionService001&pageSize="+ pageSize +"&currentPage=1&permissioinMenuId="+menuId+"&requestUid="+queryrequestUid, "", outputauthority, '');
}
function outputauthority(result){
    var outHtml = template("authorityTmpl", result);
    $("#authorityList").html(outHtml);
}

//新增权限拟态框
$("#btnAddAuthority").click(function(){
    edit="";
    addempty();
    $("#addAuthority").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
})

//确认新增
$("#btn_saveAuthority").click(function(){
    if($.formValidator.PageIsValid()) {
        var a = $("#requestUid").val();
        if (edit == "") {
            PostForm("/cwp/front/sh/permission!execute", "uid=permissionService005", "", addReturnInfon,"", 'frmMain');
        } else {
            PostForm("/cwp/front/sh/permission!execute", "uid=permissionService003&permissionId=" + edit, "", editReturnInfon, "",'frmMain');
        }
        $("#addAuthority").modal("hide");
    }
})
function addReturnInfon(result){
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "新增成功");
            isFirst = true;
            queryListauthority(menuId);
            break;
        case "1":
            tipModal("icon-cross", "新增失败");
            break;
        case "-9999":
            tipModal("icon-cross", "新增失败");
            break;
    }

}
function editReturnInfon(result){
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "修改成功");
            isFirst = true;
            queryListauthority(menuId);
            break;
        case "1":
            tipModal("icon-cross", "修改失败");
            break;
        case "-9999":
            tipModal("icon-cross", "修改失败");
            break;
    }
}
//修改权限拟态框
$(document).on("click",".editAuthority",function(){
    addempty();
    thisNum = $(this).attr("data-id");
    edit = $(this).attr("data-dataId");
    $("#addAuthority h4").html("修改权限");

    authorityEdit(menuId);
})
function authorityEdit(menuId){
    var queryrequestUid = $("#queryrequestUid").val()
    PostForm("/cwp/front/sh/permission!execute", "uid=permissionService001&pageSize="+pageSize + "&currentPage=1&permissioinMenuId="+menuId+"&requestUid="+queryrequestUid, "", outputEditAuthority, '');
}
function outputEditAuthority(result){
    if(result.returnCode == 0){
        $("#parentIdText").val(result.beans[thisNum].description);
        $("#parentId").val(result.beans[thisNum].parentId);
        $("#requestUid").val(result.beans[thisNum].requestUid);
        $("#requestService").val(result.beans[thisNum].requestService);
        $("#permissionDesc").val(result.beans[thisNum].permissionDesc);
        $("#requestMethod").val(result.beans[thisNum].requestMethod);
        $("#addAuthority").modal({
            keyboard: true,
            backdrop: 'static'
        }).on('show.bs.modal', centerModal());
        $(window).on('resize', centerModal());
    }else if(result.returnCode == "-9999"){
        tipModal("icon-cross","获取详情失败");
    }
    else{
        tipModal("icon-cross",result.returnMessage);
    }
}

//新增清空表单
function addempty(){
    $(".tipArea div").html("").attr("class","");
    $("#addAuthority h4").html("新增权限");
    $("#parentId").val("");
    $("#requestUid").val("");
    $("#requestService").val("");
    $("#permissionDesc").val("");
    $("#requestMethod").val("");
    $("#parentIdText").val("");
}

//删除权限拟态框
$(document).on("click",".delAuthority",function(){
    delId = $(this).attr("data-id");
    $("#delAuthority").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
});

$("#btnDeleteAuthority").click(function () {
    PostForm("/cwp/front/sh/permission!execute", "uid=permissionService004&permissionId="+delId, "", delAuthority, '');
});

function delAuthority(result){
    $("#delAuthority").modal("hide");
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "删除成功");
            isFirst = true;
            queryListauthority(menuId);
            break;
        case "1":
            tipModal("icon-cross", "删除失败");
            break;
        case "-9999":
            tipModal("icon-cross", "删除失败");
            break;
    }

}

//可视化组件
$('#roleList').slimScroll({
    width: 'auto', //可滚动区域宽度
    height: '730px', //可滚动区域高度
    size: '5px', //组件宽度
    alwaysVisible: true
});
$('#authorityListBody').slimScroll({
    width: 'auto', //可滚动区域宽度
    height: '600px', //可滚动区域高度
    size: '5px', //组件宽度
    alwaysVisible: true
});

//新增/修改验证
//验证
$(document).ready(function () {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#permissionDesc").formValidator({
        onfocus: "请输入权限名称",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请输入权限名称",
        onerror: "请输入权限名称"
    });
    $("#requestUid").formValidator({
        onfocus: "请输入UID",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请输入UID",
        onerror: "请输入UID"
    });
    $("#requestService").formValidator({
        onfocus: "请输入请求服务",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请输入请求服务",
        onerror: "请输入请求服务"
    });
    $("#requestMethod").formValidator({
        onfocus: "请输入请求方法",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        onempty: "请输入请求方法",
        onerror: "请输入请求方法"
    });
});


//获取菜单树构列表
function getDeptTreeModal(zNodes){
    if(zNodes!=null){
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickSelect
            }
        };
        $.fn.zTree.init($("#treeOrgModal"), setting, zNodes);
    }
}

function beforeClickSelect(treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeOrgModal");
    $("#parentIdText").val(treeNode.name);
    $("#parentIdText").blur();
    $("#parentId").val(treeNode.powerId);
    hideMenu();
    return false;
}


function getParentNodes(node,allNode){
    if(node!=null){
        allNode += ">"+node['text'];
        curNode = node.getParentNode();
        getParentNodes(curNode,allNode);
    }else{
        //根节点
        curLocation = allNode;
    }
}

$("#parentIdText").on("focus",function(){
    showMenu();
});




function showMenu() {
    var deptIdObj = $("#parentIdText");
    var deptIdOffset = $("#parentIdText").offset();
    $("#buildingModal").css({left:deptIdOffset.left + "px", top:deptIdOffset.top - 49 + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}

function hideMenu() {
    $("#buildingModal").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}


function onBodyDown(event) {
    if (!(event.target.id == "parentIdText" || event.target.id == "buildingModal" || $(event.target).parents("#buildingModal").length>0)) {
        hideMenu();
    }
}